<template>
    <div class="seckillall">
        <div class="head">
            <el-form :model="queryParams" ref="queryForm" :inline="true">
                <el-form-item label="课程名称" prop="courseId">
                    <el-select v-model="queryParams.courseId" placeholder="请选择课程名称" filterable>
                        <el-option v-for="item in courseList" :label="item.courseName" :key="item.courseId"
                            :value="item.courseId"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="学生姓名" prop="studentName">
                    <el-input v-model="queryParams.studentName" placeholder="请输入学生姓名" clearable style="width: 240px" />
                </el-form-item>


                <el-form-item>
                    <el-button type="primary" size="default" @click="searchBtn()">搜索</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button size="default" @click="resetBtn">重置</el-button>
                </el-form-item>
            </el-form>

            <div class="middle">
                <div class="add" style="margin-left: 20px;">
                    <div class="button">
                        <el-button type="primary" :icon="Plus" @click="handleAdd()" plain>新增</el-button>
                    </div>
                </div>



            </div>
            <div class="end">
                <el-table :data="tableData" row-key="classId" style="width: 100%"
                    @selection-change="handleSelectionChange">
                    <el-table-column type="selection" />
                    <el-table-column label="序号" prop="index" width="70">
                        <template #default="scope">{{ scope.$index + 1 }}</template>
                    </el-table-column>
                    <el-table-column property="className" label="班级名称" />
                    <el-table-column property="classSize" label="班级人数" />
                    <el-table-column property="courseName" label="课程名称" />
                    <el-table-column property="courseType" label="课程类型" />
                    <el-table-column property="hours" label="总学时" />
                    <el-table-column label="课程状态">
                        <template #default="scope">
                            <el-button type="success" v-if="scope.row.courseStatus == 0" plain>正常</el-button>
                            <el-button type="danger" v-else-if="scope.row.courseStatus == 1" plain>禁用</el-button>
                            <el-button type="warning" v-else plain>审核中</el-button>

                        </template>
                    </el-table-column>


                    <el-table-column label="操作" width="260">
                        <template #default="scope">

                            <el-button size="small" @click="handleSchedule(scope.row)">
                                排课
                            </el-button>

                            <el-button size="small" type="success" @click="handleEdit(scope.row)">
                                修改
                            </el-button>

                            <el-button size="small" type="primary" @click="handleClass(scope.row)">
                                分班
                            </el-button>

                        </template>
                    </el-table-column>
                </el-table>
                <div style="margin-left: 600px;">
                    <div class="demo-pagination-block">
                        <el-pagination v-model:current-page="queryParams.pageNum"
                            v-model:page-size="queryParams.pageSize" :page-sizes="[1, 2, 20, 50]"
                            layout="total, sizes, prev, pager, next, jumper" :total="total"
                            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                    </div>
                </div>

            </div>

            <el-dialog v-model="dialogVisible" :modal="true" width="800px">
                <el-form :model="formData" :rules="rules" ref="categoryForm">
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="课程名称" prop="courseId" label-width="120px">
                                <el-select v-model="formData.courseId" placeholder="请选择课程名称" filterable
                                    style="width: 100%">
                                    <el-option v-for="item in courseList" :label="item.courseName" :key="item.courseId"
                                        :value="item.courseId"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <el-col :span="12">
                            <el-form-item label="班级名称" prop="className" label-width="120px">
                                <el-input v-model="formData.className" autocomplete="off"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="班级人数" prop="classSize" label-width="120px">
                                <el-input-number v-model="formData.classSize" :min="20" :max="100"
                                    @change="handleChange" style="width: 100%" />
                            </el-form-item>
                        </el-col>

                        <el-col :span="12">
                            <el-form-item label="班级备注" prop="note" label-width="120px">
                                <el-input v-model="formData.note" autocomplete="off"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>

                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="handleCanle">取消</el-button>
                        <el-button type="primary" @click="handleConfirm">确认</el-button>
                    </div>
                </template>
            </el-dialog>

            <el-dialog v-model="deleteDialog" title="Tips" width="500">
                <span>确认要删除吗？</span>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="deleteDialog = false">取消</el-button>
                        <el-button type="primary" @click="deleteConfirm">
                            确定
                        </el-button>
                    </div>
                </template>
            </el-dialog>



            <el-dialog v-model="dialogVisiblegroup" :modal="true" width="800px">

                <el-form :model="formData" :rules="rules" ref="categoryForm">
                    <el-row>
                        <el-transfer v-model="value" :data="data" :titles="['学生列表', '已选择项']" />
                    </el-row>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="grouphandleCanle">取消</el-button>
                        <el-button type="primary" @click="grouphandleConfirm">
                            确认
                        </el-button>
                    </div>
                </template>
            </el-dialog>

            <!-- 排课弹窗 -->
            <el-dialog v-model="scheduleDialogVisible" title="排课" width="1000px">
                <el-form :model="scheduleForm" :rules="scheduleRules" ref="scheduleFormRef" label-width="100px">
                    <el-form-item label="授课教师" prop="teacherId">
                        <el-select v-model="scheduleForm.teacherId" placeholder="请选择教师" style="width: 300px">
                            <el-option v-for="item in teacherList" :key="item.userId" :label="item.teacherName"
                                :value="item.userId" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="授课教室" prop="classRoom">
                        <el-input v-model="scheduleForm.classRoom" placeholder="请选择教室" style="width: 300px"></el-input>
                    </el-form-item>

                    <el-form-item label="上课时间" prop="scheduleTime">
                        <div class="schedule-container">
                            <!-- 时间轴 -->
                            <div class="time-axis">
                                <div class="time-slot-header"></div>
                                <div class="time-slot" v-for="time in timeSlots" :key="time.value">
                                    {{ time.label }}
                                </div>
                            </div>

                            <!-- 课程表主体 -->
                            <div class="schedule-grid">
                                <!-- 表头 -->
                                <div class="schedule-header">
                                    <div class="day-cell" v-for="day in weekDays" :key="day">{{ day }}</div>
                                </div>

                                <!-- 时间格子 -->
                                <div class="schedule-body">
                                    <div v-for="(time) in timeSlots" :key="time.value" class="schedule-row">
                                        <div v-for="(day, dayIndex) in weekDays" :key="day" class="time-cell" :class="{
                                            'selected': isTimeSelected(dayIndex, time.value),
                                            'disabled': isTimeSlotDisabled(dayIndex, time.value)
                                        }" @click="toggleTimeSlot(dayIndex, time.value)">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="scheduleDialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="submitSchedule">确定</el-button>
                    </div>
                </template>
            </el-dialog>

        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Calendar, Search, Edit, Plus, Delete } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { selectAllClass, selectAllCourse, addClass, updateClass, showClass } from '@/api/class'
import { ElMessageBox } from 'element-plus'
import { selectAllStudents, getClassStudent, classManagement, getTeacher, getSchedule, scheduleManage } from '@/api/Student'



//选择框
// const selectable = ref();
const categoryForm = ref(null);
const single = ref(true)
const multiple = ref(true)
const total = ref(10);
const dialogVisible = ref(false);
const dialogVisiblegroup = ref(false);




const selected = ref("add");
//是否禁用表单
const disabled = ref(false)
const selectRow = ref([]);
const deleteDialog = ref(false)
const deleteRow = ref([])
const courseList = ref([])

const loading = ref(false) // 加载状态
const data = ref([]) // 学生列表数据
const value = ref([]) // 穿梭框选中值


onMounted(async () => {
    await selectAllCourseList();
    await selectAllClassList();
    await selectAllStudentList();
    getTeacherList();
})
//查询参数
const queryParams = ref({
    courseId: '',
    studentName: '',


    pageNum: 1,
    pageSize: 2,


})
// 表单参数
var formData = ref({
    classId: '',
    courseId: '',
    courseName: '',
    categoryId: '',
    teacherId: '',

    coursePrice: '',
    courseRemark: '',
    courseStart: '',
    className: '',
    classSize: '',
    courseType: '',
    hours: '',
    note: '',
    courseTime: 1,
})
//表格参数
const tableData = ref([])
//校验规则
const rules = {
    courseName: [
        { required: true, message: '请输入课程名称', trigger: 'blur' }
    ],
    coursePrice: [
        { required: true, message: '请输入课程价格', trigger: 'blur' },
        {
            pattern: /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/,
            message: '请输入有效的价格格式（最多两位小数）',
            trigger: 'blur'
        }
    ],

    courseName: [
        { required: true, message: '请选择课程名称', trigger: 'change' }
    ],
    className: [
        { required: true, message: '请输入班级名称', trigger: 'blur' }
    ],




    teacherId: [
        { required: true, message: '请选择授课教师', trigger: 'change' }
    ],
    categoryId: [
        { required: true, message: '请选择课程栏目', trigger: 'change' }
    ],
    courseStart: [
        { required: true, message: '请选择开始时间', trigger: 'change' }
    ],
    courseTime: [
        {
            type: 'number',
            min: 1,
            max: 72,
            message: '持续时间需在1-72周之间',
            trigger: 'blur'
        }
    ],

};

const num = ref(1)
const handleChange = function (value) {
    console.log(value)
}


// 传classId  campusId  courseId
function handleClass(row) {
    selectRow.value = row;
    const data1 = {
        classId: row.classId,
        courseId: row.courseId
    }
    getClassStudent(data1).then(res => {
        console.log(res)

        data.value = res.data.allClassStudent.map(item => ({
            key: item.studentId,
            label: item.studentName,
            disabled: false
        }))

        console.log(data.value)

        dialogVisiblegroup.value = true

        value.value = res.data.classStudent.map(item => item.studentId)


    })


}


// 分班
// 获取学生列表数据
const selectAllStudentList = async () => {
    loading.value = true
    try {
        const res = await selectAllStudents()
        console.log(res, 7777)

        // data.value = res.data.studentList.map(item => ({
        //     key: item.studentId,
        //     label: item.studentName,
        //     disabled: false
        // }))

        // if (data.value.length === 0) {
        //     ElMessage.info('暂无学生数据')
        // }
    } catch (error) {
        console.error('获取学生列表失败:', error)
        ElMessage.error('获取学生数据失败，请稍后重试')
    } finally {
        loading.value = false
    }
}





// 删除
function handleDelete(row) {
    if (row == null) {
        row = selectRow.value.map(item => {
            return item.courseId
        })
    } else {
        console.log(row)
        row = [row.courseId]
    }
    deleteRow.value = row
    deleteDialog.value = true;



}
//删除确定
function deleteConfirm() {

    deleteCourse(deleteRow.value).then(res => {
        if (res.code === 500) {
            ElMessage.error(res.message);
        } else {
            ElMessage.success("删除成功")

        }
        selectAllClassList();
    })
    deleteDialog.value = false;

}

//新增
function handleAdd() {
    dialogVisible.value = true
    selected.value = 'add'
    resetForm();
}
//每页条数变换
function handleSizeChange(val) {
    console.log("每页" + val + "条");
    queryParams.value.pageSize = val;
    queryParams.value.pageNum = 1;
    selectAllClassList();


}
//每码变换
function handleCurrentChange(val) {
    console.log("第" + val + "页")
    queryParams.value.pageNum = val;
    selectAllClassList();
}

//关闭dialog
function handleCanle() {
    dialogVisible.value = false
    // 重置表单字段
    categoryForm.value.resetFields();

    // 清除表单验证
    categoryForm.value.clearValidate();

}

//关闭dialog   分班
function grouphandleCanle() {
    dialogVisiblegroup.value = false
    // 重置表单字段
    categoryForm.value.resetFields();

    // 清除表单验证
    categoryForm.value.clearValidate();

}

// 选中某一列
function handleSelectionChange(selected) {
    console.log(selected, selected.length)
    single.value = selected.length != 1
    multiple.value = selected.length == 0
    selectRow.value = selected;

}

function handleEdit(row) {
    console.log(row, 2223344)
    const data1 = {
        classId: row.classId
    }
    formData.value.classId = row.classId
    console.log(data1, 111122226)
    dialogVisible.value = true
    showClass(data1).then(res => {
        console.log(res, 2224)
        formData.value = res.data.showClass
    })
    selected.value = 'update'
}

function handleConfirm() {
    // 验证表单 xxx
    categoryForm.value.validate((valid) => {
        // 重置表单字段
        // categoryForm.value.resetFields();
        if (valid) {
            // 表单验证通过，执行提交操作
            if (selected.value === 'add') {
                console.log(formData.value, 99);
                formData.value.campusId = sessionStorage.getItem("campusId")

                addClass(formData.value).then(res => {
                    console.log(res, 999997878);

                    if (res.code === 500) {
                        ElMessage.error(res.message);
                    } else {
                        ElMessage.success("新增成功")
                    }
                    selectAllClassList();
                    dialogVisible.value = false
                })

            } else {

                formData.value.campusId = sessionStorage.getItem("campusId")

                updateClass(formData.value).then(res => {
                    console.log(res);

                    if (res.code === 500) {
                        ElMessage.error(res.message);
                    } else {
                        ElMessage.success("修改成功")
                    }
                    selectAllClassList();
                    dialogVisible.value = false
                })
            }
        } else {
            // 表单验证失败，显示错误信息
            ElMessage.warning("请填写完整")
        }
    });


    // 清除表单验证
    categoryForm.value.clearValidate();

}

// 分班提交表单
function grouphandleConfirm() {
    dialogVisiblegroup.value = false
    const data1 = value.value
    classManagement(data1, selectRow.value.classId, selectRow.value.courseId).then(res => {
        console.log(res)
        ElMessage.success("分班成功")
    })

}

function searchBtn() {
    queryParams.value.pageNum = 1;
    selectAllClassList()
}

function resetBtn() {
    queryParams.value = {
        courseId: '',
        courseName: '',
        pageNum: 1,
        courseStatus: '',
        pageSize: queryParams.value.pageSize,
    }
    selectAllClassList()
}

function resetForm() {
    formData.value = {
        courseId: '',
        courseName: '',
    }
    disabled.value = false
    selected.value = 'add'
}


async function selectAllClassList() {

    try {
        const res = await selectAllClass(queryParams.value);
        console.log(res, 888)
        total.value = res.data.classList.total
        tableData.value = res.data.classList.records
        for (const item of tableData.value) {
            for (const element of courseList.value) {
                if (element.courseId == item.courseId) {
                    item.courseName = element.courseName
                }
            }
        }
    } catch (error) {
        console.log(error)
    }

}

async function selectAllCourseList() {
    try {
        const res = await selectAllCourse();
        courseList.value = res.data.courseList
        console.log(courseList.value, 999)
    } catch (e) {
        console.log(e)
    }

}

// 排课相关数据
const scheduleDialogVisible = ref(false)
const scheduleFormRef = ref(null)
const teacherList = ref([
    { teacherId: 1, teacherName: '张老师' },
    { teacherId: 2, teacherName: '李老师' },
    { teacherId: 3, teacherName: '王老师' },
    { teacherId: 4, teacherName: '赵老师' },
    { teacherId: 5, teacherName: '刘老师' }
])
const weekDays = ['周一', '周二', '周三', '周四', '周五']
const timeSlots = [
    { label: '8:00-10:00', value: '8-10' },
    { label: '10:00-12:00', value: '10-12' },
    { label: '14:00-16:00', value: '14-16' },
    { label: '16:00-18:00', value: '16-18' },
    { label: '19:00-21:00', value: '19-21' }
]

const scheduleForm = ref({
    teacherId: '',
    scheduleTime: [[], [], [], [], []], // 对应周一到周五的时间段
    classId: '',
    classRoom: ''
})

const scheduleRules = {
    teacherId: [
        { required: true, message: '请选择授课教师', trigger: 'change' }
    ],
    classRoom: [
        { required: true, message: '请选择授课教室', trigger: 'change' }
    ],
    scheduleTime: [
        {
            validator: (rule, value) => {
                return value.some(day => day.length > 0)
            },
            message: '请至少选择一个时间段',
            trigger: 'change'
        }
    ]
}

// 检查时间段是否已被选择
function isTimeSelected(dayIndex, timeValue) {
    return scheduleForm.value.scheduleTime[dayIndex].includes(timeValue)
}

// 检查时间段是否被禁用
function isTimeSlotDisabled(dayIndex, timeValue) {
    const selectedCount = scheduleForm.value.scheduleTime[dayIndex].length
    return selectedCount >= 2 && !isTimeSelected(dayIndex, timeValue)
}

// 切换时间段选择状态
function toggleTimeSlot(dayIndex, timeValue) {
    if (isTimeSlotDisabled(dayIndex, timeValue)) return

    const daySchedule = scheduleForm.value.scheduleTime[dayIndex]
    const index = daySchedule.indexOf(timeValue)

    if (index === -1) {
        if (daySchedule.length < 2) {
            daySchedule.push(timeValue)
        }
    } else {
        daySchedule.splice(index, 1)
    }
}

// 示例数据
const exampleSchedule = [
    // {
    //     weekday: 1,  // 周一
    //     startTime: "08:00",
    //     endTime: "10:00"
    // },
    // {
    //     weekday: 1,  // 周一
    //     startTime: "16:00",
    //     endTime: "18:00"
    // },
    // {
    //     weekday: 3,  // 周三
    //     startTime: "10:00",
    //     endTime: "12:00"
    // },
    // {
    //     weekday: 5,  // 周五
    //     startTime: "19:00",
    //     endTime: "21:00"
    // }
]

// 时间映射
const timeMap = {
    '08:00:00-10:00:00': { startTime: '08:00:00', endTime: '10:00:00' },
    '10:00:00-12:00:00': { startTime: '10:00:00', endTime: '12:00:00' },
    '14:00:00-16:00:00': { startTime: '14:00:00', endTime: '16:00:00' },
    '16:00:00-18:00:00': { startTime: '16:00:00', endTime: '18:00:00' },
    '19:00:00-21:00:00': { startTime: '19:00:00', endTime: '21:00:00' }
}

// 反向时间映射
const reverseTimeMap = {
    '08:00:00-10:00:00': '8-10',
    '10:00:00-12:00:00': '10-12',
    '14:00:00-16:00:00': '14-16',
    '16:00:00-18:00:00': '16-18',
    '19:00:00-21:00:00': '19-21'
}

// 打开排课弹窗
function handleSchedule(row) {
    selectRow.value = row;
    scheduleForm.value.classId = row.classId


    getScheduleList();
    scheduleDialogVisible.value = true

    // 重置时间选择
    scheduleForm.value.scheduleTime = [[], [], [], [], []]
}

// 获取排课列表
function getScheduleList() {
    const data1 = {
        classId: selectRow.value.classId
    }
    getSchedule(data1).then(res => {
        console.log('获取到的排课数据:', res)
        // 重置时间选择
        scheduleForm.value.scheduleTime = [[], [], [], [], []]

        // 处理返回的排课数据
        if (res.data && res.data.schedule) {
            res.data.schedule.forEach(schedule => {
                const timeKey = `${schedule.startTime}-${schedule.endTime}`
                const timeValue = reverseTimeMap[timeKey]
                if (timeValue) {
                    // weekday从1开始，数组索引从0开始，所以需要减1
                    const dayIndex = parseInt(schedule.weekday) - 1
                    scheduleForm.value.scheduleTime[dayIndex].push(timeValue)
                }
            })
            // 如果有排课数据，设置教师ID
            if (res.data.schedule[0]) {

                scheduleForm.value.teacherId = res.data.schedule[0].userId
                scheduleForm.value.classRoom = res.data.schedule[0].classRoom
            }
            else {
                scheduleForm.value.teacherId = undefined
                scheduleForm.value.classRoom = ""
            }

        }
    })
}

// 提交排课
function submitSchedule() {
    scheduleFormRef.value.validate((valid) => {
        if (valid) {
            // 转换时间格式
            const scheduleList = []
            scheduleForm.value.scheduleTime.forEach((daySchedule, dayIndex) => {
                daySchedule.forEach(timeValue => {
                    // 从时间值（如 '8-10'）获取对应的时间段
                    const [start, end] = timeValue.split('-')
                    const startTime = `${start.padStart(2, '0')}:00:00`
                    const endTime = `${end.padStart(2, '0')}:00:00`

                    scheduleList.push({
                        weekday: (dayIndex + 1).toString(), // 转为字符串，与后端格式保持一致
                        startTime: startTime,
                        endTime: endTime,
                        userId: scheduleForm.value.teacherId,
                        classId: scheduleForm.value.classId,
                        classRoom: scheduleForm.value.classRoom,
                        scheduleStatus: 0
                    })
                })
            })

            console.log('排课时间列表:', scheduleList)
            scheduleManage(scheduleList).then(res => {
                console.log(res)
            })
            // 这里可以添加提交排课的接口调用
            // submitScheduleApi({
            //     scheduleList: scheduleList
            // })

            ElMessage.success('排课成功')
            scheduleDialogVisible.value = false
        }
    })
}

function getTeacherList() {
    const data1 = {
        campusId: sessionStorage.getItem("campusId")
    }
    getTeacher(data1).then(res => {
        console.log(res, 890)
        teacherList.value = res.data.showTeacher
    })
}
</script>

<style scoped>
.seckillall {
    height: 100%;
    width: 100%;
    /* width: calc(100% - 50px); */
    /* background-color: pink; */
    float: left;
}

.head {
    margin-top: 20px;
    margin-left: 20px;
    width: calc(100% - 50px);
}

.middle {
    width: 100%;
    height: 8vh;
    /* background-color: antiquewhite; */
    margin-bottom: 20px;
}

.add {
    margin-top: 15px;
    margin-left: 45px;
    width: 5%;
    height: 50%;
    float: left;
}

.end {
    float: left;
    width: calc(100% - 50px);
}

.schedule-container {
    display: flex;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    margin-top: 10px;
    width: 100%;
}

.time-axis {
    width: 120px;
    border-right: 1px solid #dcdfe6;
    background-color: #f5f7fa;
    flex-shrink: 0;
}

.time-slot-header {
    height: 40px;
    border-bottom: 1px solid #dcdfe6;
}

.time-slot {
    height: 100px;
    line-height: 100px;
    text-align: center;
    border-bottom: 1px solid #dcdfe6;
    font-size: 14px;
}

.schedule-grid {
    flex: 1;
    min-width: 0;
}

.schedule-header {
    display: flex;
    background-color: #f5f7fa;
    border-bottom: 1px solid #dcdfe6;
}

.day-cell {
    flex: 1;
    height: 40px;
    line-height: 40px;
    text-align: center;
    border-right: 1px solid #dcdfe6;
    font-weight: bold;
    font-size: 16px;
    min-width: 120px;
}

.schedule-body {
    display: flex;
    flex-direction: column;
}

.schedule-row {
    display: flex;
    height: 100px;
    border-bottom: 1px solid #dcdfe6;
}

.time-cell {
    flex: 1;
    border-right: 1px solid #dcdfe6;
    cursor: pointer;
    transition: all 0.3s;
    min-width: 120px;
    height: 100px;
}

.time-cell:hover:not(.disabled) {
    background-color: #ecf5ff;
}

.time-cell.selected {
    background-color: #409eff;
}

.time-cell.disabled {
    background-color: #f5f7fa;
    cursor: not-allowed;
    opacity: 0.6;
}

.time-cell:last-child {
    border-right: none;
}

:deep(.el-form-item__content) {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
}
</style>